//
//  EvaluateViewController.m
//  homeland
//
//  Created by caesar on 14-8-5.
//  Copyright (c) 2014年 xzysun. All rights reserved.
//

#import "EvaluateViewController.h"
#import "ListViewController.h"
#import "UserInfoService.h"

@interface EvaluateViewController ()
//变量区
//=========================
//定义一个变量来记录下一个将要添加的控件的位置
@property (assign, nonatomic) int nextY;
//实体uid
@property (strong, nonatomic) NSString *itemEntityId;
//请求参数集
@property (assign, nonatomic) NSMutableDictionary *params;
//评价记录集
@property (assign, nonatomic) NSMutableDictionary *jsonData;
//提交按钮
@property (strong, nonatomic) IBOutlet UIButton *postBtn;
//更多按钮
@property (strong, nonatomic) UIButton *labelBtn;

@end

@implementation EvaluateViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    self.title = @"社区服务网格员评价";
    [self configView];
}

/**数据渲染展示*/
-(void)configView{
     _nameLabel.text = [CommonUtil dealNullObject:[_config objectForKey:@"name"]];
    _checkButtonValue = @"0";
     _rg =[[ RadioGroup alloc ] init ];
    _cb0 = [[ CheckButton alloc ] initWithFrame : CGRectMake (20, CGRectGetMaxY(self.headView.frame)+10, 125, 32)];
    [self initRadioButton:_cb0   lableText:@"满意" setValue:@"0"];
    _cb1 = [[ CheckButton alloc ] initWithFrame : CGRectMake (20, CGRectGetMaxY(_cb0.frame)+10, 125, 32)];
    [self initRadioButton:_cb1   lableText:@"基本满意" setValue:@"1"];
    _cb2 = [[ CheckButton alloc ] initWithFrame : CGRectMake (20, CGRectGetMaxY(_cb1.frame)+10, 125, 32)];
    [self initRadioButton:_cb2    lableText:@"不满意" setValue:@"2"];

    [self.mainPanel addSubview: _cb0];
    [self.mainPanel addSubview: _cb1];
    [self.mainPanel addSubview: _cb2];
    
    //内容view
    _opinionLabel.frame = CGRectMake (_opinionLabel.frame.origin.x, CGRectGetMaxY(_cb2.frame)+10, _opinionLabel.frame.size.width, _opinionLabel.frame.size.height);
    _contentTextView.frame = CGRectMake (_contentTextView.frame.origin.x, CGRectGetMaxY(_opinionLabel.frame)+10, _contentTextView.frame.size.width, _contentTextView.frame.size.height);
    _contentTextView.layer.borderColor = [CommonUtil stringToColor:@"#C0C0C0"].CGColor;
    _contentTextView.layer.borderWidth =1.0;
    _contentTextView.layer.cornerRadius =5.0;
    
    _nextY+= (CGRectGetMaxY(self.contentTextView.frame));//下一元素显示的位置

    //设置评价状态及获取评价记录
    [self getWeeEvaluate];
}

//设置评价状态及获取评价记录并完成页面展示
- (void)getWeeEvaluate{
    UserInfo *userINfo = [UserInfoService getUserInfoService].userInfo;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[CommonUtil formatDateStrStyle:@"yyyyMM"] forKey:@"yearWeek"];
    [params setValue:[_config objectForKey:@"uid"] forKey:@"uid"];
    [params setValue:userINfo.Id forKey:@"userId"];
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:SERVER_URL_COMMUNITY_WAITER_EVALUATE_QUERY_WEEK customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        NSDictionary *json = [completedOperation responseJSON];
        BOOL isSubmit = [CommonUtil dealNullObject:[json objectForKey:@"isSubmit"]].boolValue;
        //评价记录
        _jsonData =[json objectForKey:@"list"];
        if (isSubmit) {
             NSDictionary *dic = [json objectForKey:@"bean"];
            int evaluate = [[dic objectForKey:@"evaluate"]intValue];
            switch (evaluate) {
                case 0:
                    _cb0.checked = YES;
                    break;
                case 1:
                    _cb1.checked = YES;
                    break;
                case 2:
                    _cb2.checked = YES;
                    break;
                default:
                    break;
            }
            _cb0.enable = NO;
            _cb1.enable = NO;
            _cb2.enable = NO;
            _postBtn.hidden = YES;
            _contentTextView.text = [dic objectForKey:@"content"];
            _contentTextView.editable = false;
            
            //展示评价记录
            [self showEvaluateRecord];
        }else{
            [self createOpinionBtn];
        }
        
        CGFloat totalHeight = MAX(_nextY, CGRectGetHeight(self.scrollView.frame));
        self.mainPanel.frame = CGRectMake(0.0, 0.0, 320.0, totalHeight);
        [self.scrollView addSubview:self.mainPanel];
        self.scrollView.contentSize = self.mainPanel.frame.size;
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        
    }];
    [currentEngine enqueueOperation:op];
}

//展示评价记录列表
-(void)showEvaluateRecord{
    //评价记录内容展示
    if (_jsonData && [_jsonData count]>0) {
        //文字tip
        //--------------
        NSString *labelStr = @"评价记录";
        UIButton *labelBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, _nextY, 250, 32)];
        [labelBtn setTitle:labelStr forState:UIControlStateNormal];
        labelBtn.titleLabel.font = [UIFont boldSystemFontOfSize: 17.0];
        [labelBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        labelBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft ;//文字水平居左
        labelBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter ;//文字垂直居中
        
        [self.mainPanel addSubview:labelBtn];
        
        _nextY += 37;//与下一元素的垂直间距为37
        
        int itemNum = 1;
        for(NSMutableDictionary *nsd in _jsonData){
            if (itemNum<6) {
                UIView *recordPanel = [[UIView alloc] initWithFrame:CGRectMake(10, _nextY, 300, 32)];
                recordPanel.layer.borderWidth = 1;
                recordPanel.layer.borderColor = [[UIColor lightGrayColor] CGColor];
                recordPanel.layer.cornerRadius = 0;
                int subNextY = 5;
                //用户及评价
                UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(5, subNextY, 150, 32)];
                NSString * labelStr = [CommonUtil dealNullObject:[nsd objectForKey:@"userName"]];
                int evaluate = [CommonUtil dealNullObject:[nsd objectForKey:@"evaluate"]].intValue;
                switch (evaluate) {
                    case 0:
                        labelStr = [[NSString stringWithFormat:@"%@：",labelStr] stringByAppendingString:@"满意"];
                        break;
                    case 1:
                        labelStr = [[NSString stringWithFormat:@"%@：",labelStr] stringByAppendingString:@"基本满意"];
                        break;
                    case 2:
                        labelStr = [[NSString stringWithFormat:@"%@：",labelStr] stringByAppendingString:@"不满意"];
                        break;
                    default:
                        break;
                }
                label.font = [UIFont systemFontOfSize:14];//字体大小
                label.textAlignment = NSTextAlignmentLeft;//文字居左显示
                label.text = labelStr;
                label.textColor = [UIColor blackColor];
                [recordPanel addSubview:label];
                
                //评价时间
                UILabel* timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(155,label.frame.origin.y, 140, label.frame.size.height)];
                timeLabel.font = [UIFont systemFontOfSize:14];//字体大小
                timeLabel.textAlignment = NSTextAlignmentLeft;//文字居左显示
                timeLabel.text = [CommonUtil formatDateStr:[nsd objectForKey:@"insertTime"] style:@"yyyy-MM-dd HH:mm"];;
                timeLabel.textColor = [UIColor blackColor];
                [recordPanel addSubview:timeLabel];
                
                subNextY+=label.frame.size.height+5;
                
                //分割线
                UITextView* spiritLine = [[UITextView alloc] initWithFrame:CGRectMake(5, subNextY, 290, 0.5)];
                spiritLine.backgroundColor = [UIColor blackColor];
                [recordPanel addSubview:spiritLine];
                subNextY += 5.5;//与下一元素的垂直间距为5.5
                
                //评价意见
                UILabel* opinionLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, subNextY, 290, 32)];
                labelStr = [CommonUtil dealNullObject:[nsd objectForKey:@"content"]];
                //300为UILabel的宽度，100是预设的一个高度，表示在这个范围内
                CGSize labelSize = [labelStr sizeWithFont:[UIFont systemFontOfSize:14]
                                        constrainedToSize:CGSizeMake(290.0, 100)
                                            lineBreakMode:NSLineBreakByWordWrapping];
                opinionLabel.font = [UIFont systemFontOfSize:14];//字体大小
                opinionLabel.textAlignment = NSTextAlignmentLeft;//文字居左显示
                opinionLabel.numberOfLines = 0;//表示label可以多行显示
                opinionLabel.lineBreakMode = NSLineBreakByWordWrapping;//换行模式，与上面的计算保持一致。
                opinionLabel.frame = CGRectMake(opinionLabel.frame.origin.x, opinionLabel.frame.origin.y, opinionLabel.frame.size.width, labelSize.height);//保持原来Label的位置和宽度，只是改变高度。
                opinionLabel.text = labelStr;
                opinionLabel.textColor = [UIColor blackColor];
                [recordPanel addSubview:opinionLabel];
                
                subNextY+=labelSize.height+10;
                recordPanel.frame = CGRectMake(recordPanel.frame.origin.x, recordPanel.frame.origin.y, recordPanel.frame.size.width, subNextY+10);
                [self.mainPanel addSubview:recordPanel];
                
                _nextY += recordPanel.frame.size.height+10;//与下一元素的垂直间距
            }
            itemNum++;
        }
        
        if ([_jsonData count]>5){
            NSString *labelStr = @"查看更多记录";
            _labelBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, _nextY, 300, 32)];
            [_labelBtn setTitle:labelStr forState:UIControlStateNormal];
            _labelBtn.titleLabel.font = [UIFont boldSystemFontOfSize: 17.0];
            [_labelBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
            _labelBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter ;//文字水平居中
            _labelBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter ;//文字垂直居中
            _labelBtn.contentEdgeInsets = UIEdgeInsetsMake(0,0, 0, 0);
            //添加事件
            [_labelBtn addTarget:self action:@selector(jumpToMoreRecord:) forControlEvents:UIControlEventTouchUpInside];
            
            _labelBtn.layer.borderWidth = 1;
            _labelBtn.layer.borderColor = [[UIColor lightGrayColor] CGColor];
            _labelBtn.layer.cornerRadius = 0;
            
            [self.mainPanel addSubview:_labelBtn];
            
            _nextY += 40;//与下一元素的垂直间距为40
        }
    }
}

//初始化单选框
-(void)initRadioButton:(CheckButton*)cb  lableText:(NSString*)lableText setValue:(NSString*)value{
    cb.label.font = [UIFont systemFontOfSize:15];//字体大小
    cb.label.textAlignment = NSTextAlignmentLeft;//文字居左显示
    cb.label.numberOfLines = 0;//表示label可以多行显示
    cb.label.lineBreakMode = NSLineBreakByWordWrapping;//换行模式，与上面的计算保持一致。
    cb.label.text = lableText;
    cb.label.textColor = [UIColor orangeColor];
    cb.style = CheckButtonStyleRadio ;
    cb. value = value;
    [cb addTarget:self action:@selector(radioClicked:) forControlEvents:UIControlEventTouchUpInside];
    [ _rg add :cb];
}

/**单选框事件*/
-(void)radioClicked:(id)sender{
    CheckButton *cb = sender;
    _checkButtonValue = cb.value;
}
/**
 *创建提交按钮
 */
- (void)createOpinionBtn{
    int height = iPhone5 ? 0 : 88 ;
    //生成底部按扭-意见提交按钮
    _postBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,460 - height, 320, 44)];
    [_postBtn setBackgroundImage:[UIImage imageNamed:@"btnImage.png"] forState:0];
    [_postBtn setTitle:@"提交" forState:0];
    [_postBtn addTarget:self action:@selector(postButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_postBtn];
    _nextY+=50;
}
//提交按钮
- (IBAction)postButton:(id)sender {
    if (!_contentTextView.text || [_contentTextView.text isEqualToString:@""] || _contentTextView.text.length == 0) {
        [self showAlertWithTitle:@"提示" Msg:@"请输入评价内容"];
        return;
    }
    [self postEvaluate];
}
//提交评价
- (void)postEvaluate{
    UserInfo *userINfo = [UserInfoService getUserInfoService].userInfo;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:_checkButtonValue forKey:@"evaluate"];
    [params setValue:[_config objectForKey:@"uid"] forKey:@"uid"];
    [params setValue:userINfo.Id forKey:@"userId"];
    [params setValue:userINfo.userName forKey:@"userName"];
    [params setValue:_contentTextView.text forKey:@"content"];
    
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:SERVER_URL_COMMUNITY_WAITER_EVALUATE_ADD  customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        
        
        NSDictionary *json = [completedOperation responseJSON];
        BOOL isSuccess = [CommonUtil dealNullObject:[json objectForKey:@"isSuccess"]].boolValue;
        if (isSuccess) {
            [self showAlertWithTitle:@"提示" Msg:@"提交成功"];
            
            //刷新当前页
            [self refreshPageOne];
        }else{
            [self showAlertWithTitle:@"提示" Msg:@"提交失败"];
        }
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        
    }];
    [currentEngine enqueueOperation:op];
}

//查看更多评价
-(void)jumpToMoreRecord:(id)sender{
    ListViewController *crVC =[[ListViewController alloc]initWithNibName:@"ListViewController" bundle:nil];
    NSDictionary *dic = @{@"key":@"社区服务网格员评价列表",@"uid":[_config objectForKey:@"uid"]};
    crVC.config = dic;
    [self.navigationController pushViewController:crVC animated:YES];
}
//评价提交成功后，刷新当前页
- (void)refreshPageOne{
    [self.view setNeedsDisplay];
    _postBtn.hidden = YES;
    _contentTextView.editable = false;
    
    //展示评价记录
    [self getWeeEvaluate];
}

@end
